var express = require('express');
var app = express();
var callfile = require('child_process');
var fs = require('fs');

const defaultsWriteOpt = {
  flags: 'w',
  defaultEncoding: 'utf8',
  fd: null,
  mode: 0o666,
  autoClose: true
};


/**
*  1)  更新alpha.m
   2)  更新m站
   3)  更新admin-web-app.sh
   4） api-web-app.sh
   5） home-web-app.sh
   6） wap-web-app.sh
**/
//  主页输出 "Hello World"
app.get('/pub_alpha_m', function (req, res) {
  console.log("alpha 的测试服更新");
  res.write('alpha 的测试服更新');
  startExec("alpha 的测试服更新",
    "/datas/xvdb2/moocMobileApp/asynctools/alpha.sh",
    "pub_alpha_m",
    req,
    res
  )
})


//  POST 请求
app.get('/pub_m', function (req, res) {
  console.log("正式服的m站更新....");
  res.write('正式服的m站更新....');
  startExec("正式服的m站更新....",
    "/datas/xvdb2/moocMobileApp/asynctools/stable.sh",
    "pub_m",
    req,
    res
  )
})

//  /del_user 页面响应
app.get('/pub_admin_web_app', function (req, res) {
  console.log("后台的管理员界面更新");
  res.write('后台的管理员界面更新');
  startExec("后台的管理员界面更新",
    "/datas/xvdb2/sufun4test/shelltest/web-async/admin-web-app.sh",
    "pub_admin_web_app",
    req,
    res
  )
})

//  /list_user 页面 GET 请求
app.get('/pub_api_web_app', function (req, res) {
  console.log("pc站的api接口开始更新");
  res.write('pc站的api接口开始更新');
  startExec("pc站的api接口开始更新",
    "/datas/xvdb2/sufun4test/shelltest/web-async/api-web-app.sh",
    "pub_api_web_app",
    req,
    res
  )
})

// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/pub_home_web_app', function (req, res) {
  console.log("pc站的前端开始执行更新");
  res.write('pc站的前端开始执行更新');
  startExec("pc站的前端开始执行更新",
    "/datas/xvdb2/sufun4test/shelltest/web-async/home-web-app.sh",
    "pub_home_web_app",
    req,
    res
  )
})
//请求
app.get('/pub_wap_web_app', function (req, res) {
  console.log("老站的wap站开始更新");
  res.write('老站的wap站开始更新');
  startExec("老站的wap站开始更新", "/datas/xvdb2/sufun4test/shelltest/web-async/wap-web-app.sh"
    , "pub_wap_web_app", req, res);
})

app.get('/pub_test', function (req, res) {
  console.log("开启网站更新测试");
  res.write('开启网站更新测试');
  startExec("开启网站更新测试", "/datas/xvdb2/moocMobileApp/asynctools/alpha_test.sh", "pub_test", req, res);
})

function startExec(tips, bash_path, task_name, req, res) {
  var taskinfo = readDiskFile(task_name);
  if (taskinfo === null) {
    res.write(tips);
    writeDisk(task_name, "the task is starting", 1);
    callfile.execFile(bash_path, (error, stdout, stderr) => {
      if (error) {
        writeDisk(task_name, "taskProblems-->" + error, 0);
      }
      else {
        writeDisk(task_name, "the task had finish" + task_name, 0)
      }
    });
  }
  else {
    if (taskinfo.status == 1) {
      res.write("the task of " + tips + "  is running");
      res.write(readDiskFile(task_name));
    }
    else {
      res.write(tips + "  task is start running");
      callfile.execFile(bash_path, (error, stdout, stderr) => {
        if (error) {
          writeDisk(task_name, "taskProblems-->" + error, 0);
        }
        else {
          writeDisk(task_name, "the task had finish" + task_name, 0)
        }
      });
    }
  }
}

app.get("/start_task", function (req, res) {
  //判断任务是不是在执行
  var taskinfo = readDiskFile("start_task");
  if (taskinfo === null) {
    //任务没有启动
    console.log("we starting the task ");

    writeDisk("start_task", "the task is starting", 1);

    res.send("Starting test task");
  } else {
    //任务启动中----->
    console.log("the task is running ");
    res.send("the task is running hold on ");
  }
})

app.get("/end_task", function (req, res) {
  writeDisk("start_task", "测试任务结束ing", 0);
  res.send("任务结束.....");
})


/**
 * 
 * 
 * 
 * @param {any} filename 
 * @param {any} content 
 * @param {any} status    0:任务未启动中  1:任务正在跑着
 */
function writeDisk(filename, content, status) {
  var info = new Object();
  info.content = content;
  info.status = status;
  var writeStream = fs.createWriteStream(filename + ".data", defaultsWriteOpt);   //JSON.stringify(info)
  writeStream.write(JSON.stringify(info));

}
/**
 * 写文件到磁盘上面
 * 
 * @param {any} filename 
 */
function readDiskFile(filename) {
  if (fsExistsSync(filename + ".data")) {
    var data = fs.readFileSync(filename + ".data");
    if (data.status) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }
  else {
    return null;
  }
}

//检测文件或者文件夹存在 nodeJS
function fsExistsSync(path) {
  try {
    fs.accessSync(path, fs.F_OK);
  } catch (e) {
    return false;
  }
  return true;
}

var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("欢迎访问发版本接口", host, port)
})